/*
 * Assignment04.c
 *
 * Created: 4/13/2015 5:43:58 PM
 *  Author: Jeevake Attapattu
 */ 


#define F_CPU 8000000UL //XTAL =8MHz

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>


void startTimer1(void)
{
	TCNT1 = 0;//start value for timer1
	//WGM 1000 PWM, phase and frequency correct OCR1A is TOP
	//COM1A 10 clear OC1A on compare match when up counting, set on compare match when down counting
	TCCR1A = (1<<COM1A1)|(0<<COM1A0)|(0<<WGM11)|(0<<WGM10);
	TCCR1B = (1<<CS10)|(1<<WGM13)|(0<<WGM12);//no pre-scalar
}

void startTimer0(void)
{
	TCNT0 = 0;//start value for timer0
	//WGM 111 fast PWM OCRA is TOP
	//COM0A 01 toggle OC0A on compare match
	//COM0B 10 clear OC0B on compare match set at bottom
	TCCR0A = (1<<COM0B1)|(0<<COM0B0)|(0<<COM0A1)|(1<<COM0A0)|(1<<WGM01)|(1<<WGM00);
	TCCR0B = (1<<CS00)|(1<<WGM02);//no pre-scalar
}

void startTimer2(void)
{
	TCNT2 = 0;//start value for timer2
	//WGM 111 fast PWM OCRA is TOP
	//COM2A 01 toggle OC2A on compare match
	//COM2B 10 clear OC2B on compare match set at bottom
	TCCR2A = (1<<COM2B1)|(0<<COM2B0)|(0<<COM2A1)|(1<<COM2A0)|(1<<WGM21)|(1<<WGM20);
	TCCR2B = (1<<CS20)|(1<<WGM22);//no pre-scalar
}

void stopTimers(void)
{
	TCCR1B = (0<<CS10);//use pre-scalar of 0
	TCCR0B = (0<<CS00);//use pre-scalar of 0
	TCCR2B = (0<<CS20);//use pre-scalar of 0
}




int main(void)
{
	DDRB |= 1<<PB1|1<<PB3;//set OC1A and OC2A to outputs
	DDRD |=1<<PD6|1<<PD5|1<<PD3;//set OC0A, OC0B, 0C2B to output
	sei();//enable interrupts
	
	while(1)
	{
		for(int i=26; i<255; i+=26)
		{
			for(int x = 1; x<10; x+=2)
			{
				ICR1 = i;//set top for timer 1
				OCR1A = (int)((float)i*(float)x/10);//set duty cycle for timer 1
				startTimer1();//restart timer 1
				for (int j = 26; j<255; j+=26)
				{
					OCR0A = j;//set top for timer 0
					for (int y = 0; y<j; y+=(int)((float)j/5))
					{
						OCR0B = y;// set duty cycle for timer 0
						startTimer0();//restart timer 0
						for (int k = 26; k<255;k+=26)
						{
							OCR2A = k;//set top for timer 2
							for (int z = 0; z<k; z+=(int)k/5.0)
							{
								OCR2B = z; //set duty cycle for timer 2
								startTimer2();//restart timer 2
								_delay_ms(25);		//use AVR studio library delay
							}

						}
					}

				}
				
			}
		}

	}
	return 0;
}
